package com.example.spring.jpa.ast.handle;

import com.example.spring.jpa.ast.AstExpression;
import com.example.spring.jpa.ast.AstNode;
import com.example.spring.jpa.ast.MinorOperation;
import com.example.spring.jpa.ast.operation.AstSymmetryOperation;

/**
 * @author: orange
 * @create: 2023-07-22 23:49
 * @description:
 */
public class SymmetryHandle extends AbstractOperationHandle {
    private boolean match = false;
    private final String[] operations = {
            MinorOperation.NOT$1.getOperation(),
            MinorOperation.NOT$2.getOperation(),
    };

    @Override
    public boolean isMatch() {
        return this.match;
    }

    @Override
    public AstNode handle(String exp, int start) throws Exception {
        if (exp == null || exp.length() == 0) return null;
        int bracket = 0;
        for (int i = start; i < exp.length(); i++) {
            if (exp.charAt(i) == '(') bracket++;
            else if (exp.charAt(i) == ')') bracket--;
            if (bracket == 0) {
                String ope = indexOfOperation(exp, i);
                this.match = ope != null;
                if (this.match) {
                    AstSymmetryOperation astSymmetryOperation = AstSymmetryOperation.getInstance(ope);
                    AstExpression astExpression = new AstExpression(exp.substring(i + ope.length()));
                    astSymmetryOperation.setAstNode(astExpression);
                    astSymmetryOperation.setSentence(ope);
                    return astSymmetryOperation;
                }
            }
        }
        return null;
    }

    @Override
    public String[] operations() {
        return this.operations;
    }

    @Override
    public int order() {
        return 2;
    }
}
